import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class TempPathUtil {
  /// 获取临时目录路径
  static Future<String> get tempDirPath async {
    final Directory tempDir = await getTemporaryDirectory();
    return tempDir.path;
  }

  /// 生成唯一的临时文件路径
  static Future<String> generateTempFilePath(
      {String? fileName, String? extension}) async {
    final String tempDir = await tempDirPath;
    final String uniqueId = DateTime.now().millisecondsSinceEpoch.toString();

    String finalFileName = fileName ?? 'download_$uniqueId';
    if (extension != null && !finalFileName.endsWith('.$extension')) {
      finalFileName = '$finalFileName.$extension';
    }

    return path.join(tempDir, finalFileName);
  }

  /// 生成固件下载的临时文件路径
  static Future<String> generateFirmwareTempPath({
    required String deviceName,
    required String version,
    String extension = 'bin',
  }) async {
    // 清理设备名称，移除特殊字符
    final cleanDeviceName = deviceName.replaceAll(RegExp(r'[^a-zA-Z0-9]'), '_');
    final fileName = '${cleanDeviceName}_v$version';

    return generateTempFilePath(
      fileName: fileName,
      extension: extension,
    );
  }

  /// 检查临时文件是否存在
  static Future<bool> tempFileExists(String filePath) async {
    final file = File(filePath);
    return await file.exists();
  }

  /// 删除临时文件
  static Future<void> deleteTempFile(String filePath) async {
    try {
      final file = File(filePath);
      if (await file.exists()) {
        await file.delete();
      }
    } catch (e) {
      print('删除临时文件失败: $e');
    }
  }

  /// 清理所有临时文件
  static Future<void> clearAllTempFiles() async {
    try {
      final tempDir = await getTemporaryDirectory();
      final files = tempDir.listSync();

      for (var file in files) {
        if (file is File) {
          await file.delete();
        }
      }
    } catch (e) {
      debugPrint('清理临时文件失败: $e');
    }
  }

  /// 获取临时目录使用情况
  static Future<Map<String, dynamic>> getTempDirUsage() async {
    final tempDir = await getTemporaryDirectory();
    final files = tempDir.listSync();

    int totalSize = 0;
    int fileCount = 0;

    for (var file in files) {
      if (file is File) {
        totalSize += await file.length();
        fileCount++;
      }
    }

    return {
      'fileCount': fileCount,
      'totalSize': totalSize,
      'totalSizeMB': (totalSize / (1024 * 1024)).toStringAsFixed(2),
      'path': tempDir.path,
    };
  }
}
